﻿using FieldTools.Client.Business.IBusiness;
using FieldTools.Client.Entity.MyQQ;
using FieldTools.MyQQ.Core.HttpAPI;
using FieldTools.Util;
using System.Text;
using System.Text.RegularExpressions;

namespace FieldTools.Client.Business.Business
{
    public class MyQQHttpApiBus : BaseBus, IMyQQHttpApiBus, ITransientDependency
    {
        public MyQQHttpApiBus()
        {

        }

        public async Task<MyQQHttpApiReturnInfo> MessageHandling(CallbackMyQQHttpPost myqqpost, MyQQHttpApiRequestInfo info)
        {
            //由于是采用每个机器人主人关联组都执行一次的方式，因此这里要避免重复执行
            if ((myqqpost.MQ_robot != info.RobotQQ) && !info.RobotQQ.IsNullOrEmpty()) return new();

            //解析数据
            string MQ_fromID = myqqpost.MQ_fromID;
            string MQ_fromQQ = myqqpost.MQ_fromQQ;
            string MQ_msg = myqqpost.MQ_msg.IsUTF8() ? System.Web.HttpUtility.UrlDecode(myqqpost.MQ_msg, System.Text.Encoding.UTF8) : myqqpost.MQ_msg;
            string MQ_msgData = myqqpost.MQ_msgData;
            string MQ_msgID = myqqpost.MQ_msgID;
            string MQ_msgSeq = myqqpost.MQ_msgSeq;
            string MQ_passiveQQ = myqqpost.MQ_passiveQQ;
            string MQ_robot = myqqpost.MQ_robot;
            string MQ_type = myqqpost.MQ_type;
            string MQ_type_sub = myqqpost.MQ_type_sub;

            int.TryParse(MQ_type, out int a);
            myqqpost.MQ_msg = MQ_msg;

            //js脚本的配置
            if (GlobalParm.IsHandleJSForMyQQ)
            {
                var objs = new List<object>();
                try
                {
                    var ParmsJSON = myqqpost.ToJson();
                    var parms = JsonExtention.DeserializeStringToObjectArray(ParmsJSON);
                    var jsRes = await JSHelper.RunJsFromFile(GlobalParm.JsFilePathForMyQQ, "MyQQPluginRquest", parms);
                    Console.WriteLine(jsRes);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("js脚本执行异常：" + ex.Message);
                }
            }
            //内部的自定义回复
            await CustonOrderRequest(myqqpost, info);
            Console.WriteLine("收到来自<" + MQ_fromQQ + ">的消息:" + MQ_msg);

            return new();//1=其他插件可继续处理此条消息，2=拦截信息，此条消息不再分发给其他插件，其他插件将不能再处理

        }

        public async Task<MyQQHttpApiReturnInfo> MessageHandlingByClient(CallbackMyQQHttpPost myqqpost)
        {
            if (File.Exists("ClientConfig.json"))
            {
                string jsonStr = JsonExtention.GetAppsettingJson("MyQQHttpApiConfigs", "ClientConfig.json") ?? "";
                var myQQHttpApiConfigs = jsonStr.ToObject<List<RobotConfig>>();
                if (myQQHttpApiConfigs.Any())
                {
                    //遍历所有框架
                    foreach (var myQQHttpApiConfig in myQQHttpApiConfigs)
                    {
                        //遍历所有机器人以及主人的组合
                        foreach (var robotMasterqq in myQQHttpApiConfig.RobotMasters)
                        {
                            MyQQHttpApiRequestInfo myQQHttpApiRequestInfo = new()
                            {
                                Posturl = myQQHttpApiConfig.Posturl,
                                Token = myQQHttpApiConfig.Token,
                                RobotQQ = robotMasterqq.RobotQQ,
                                MasterQQ = robotMasterqq.MasterQQ
                            };
                            await MessageHandling(myqqpost, myQQHttpApiRequestInfo);
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("未找到配置文件ClientConfig.json，请确认文件位于工作目录下");
            }
            return new();

        }
        /// <summary>
        /// 判断是否被艾特
        /// </summary>
        /// <param name="myqqpost"></param>
        /// <returns></returns>
        private static bool IsAt(CallbackMyQQHttpPost myqqpost)
        {
            string MQ_msg = myqqpost.MQ_msg.IsUTF8() ? System.Web.HttpUtility.UrlDecode(myqqpost.MQ_msg, System.Text.Encoding.UTF8) : myqqpost.MQ_msg;
            string MQ_robot = myqqpost.MQ_robot;
            if (MQ_msg.Contains("@" + MQ_robot)) return true;
            else return false;
        }

        #region 预定义接口式插件，线上线下均可调通
        /// <summary>
        /// 自定义指令回复,內部暂时仅处理私聊信息与群聊信息，其他的待补充
        /// </summary>
        /// <param name="myqqpost"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task CustonOrderRequest(CallbackMyQQHttpPost myqqpost, MyQQHttpApiRequestInfo info)
        {
            if (myqqpost.MQ_type != "1" && myqqpost.MQ_type != "2") return;
            //获取配置中自定义指令初始值
            string clientConfigStr = JsonExtention.GetAppsettingJson("ClientConfig.json") ?? "";
            //
            //
            //
            //
            //注意替换为缓存获取配置的模式
            //
            //
            //
            //
            //
            var myQQHttpApiConfigs =  new List<RobotConfig>();
            foreach (var httpConfig in myQQHttpApiConfigs)
            {
                string MQ_msg = myqqpost.MQ_msg.IsUTF8() ? System.Web.HttpUtility.UrlDecode(myqqpost.MQ_msg, Encoding.UTF8) : myqqpost.MQ_msg;

                MyqqHttpApi myqqHttpApi = new(info.Posturl, info.Token);
                foreach (var custonOrder in httpConfig.CustonOrders)
                {
                    //启用情况判断，全匹配
                    if (MQ_msg == custonOrder.Keyword && custonOrder.IsOn)
                    {
                        _ = int.TryParse(myqqpost.MQ_type, out int a);
                        //仅被私聊触发
                        if (custonOrder.IsPrivate)
                        {
                            if (a == 1)
                            {
                                await parseCustonOrderRequest(myqqpost, info, myqqHttpApi, custonOrder);
                            }
                            continue;
                        }
                        //仅被艾特触发，群聊时候
                        if (custonOrder.IsAt)
                        {
                            if (a == 2)
                            {
                                if (IsAt(myqqpost))
                                {
                                    await parseCustonOrderRequest(myqqpost, info, myqqHttpApi, custonOrder);
                                }
                            }
                        }
                        else
                        {
                            await parseCustonOrderRequest(myqqpost, info, myqqHttpApi, custonOrder);
                        }

                    }
                }
            }
        }


        /// <summary>
        /// 获取淘宝买家秀
        /// </summary>
        /// <param name="myqqpost"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<string> GetBuyersShow(CallbackMyQQHttpPost myqqpost, MyQQHttpApiRequestInfo info)
        {
            var res = HttpHelper.GetData("https://api.uomg.com:443/api/rand.img3?sort=%E8%83%96%E6%AC%A1%E7%8C%AB&format=json", null, null);
            BuyersShow buyersShow = res.ToObject<BuyersShow>();
            if (buyersShow.code == "1")
            {
                MyqqHttpApi myqqHttpApi = new(info.Posturl, info.Token);
                string url = buyersShow.imgurl;
                string imgurl = buyersShow.imgurl.Replace(" ", string.Empty).Replace(@"\", string.Empty);
                await SendMsgConver(myqqpost, myqqHttpApi, $"[pic={imgurl}]");

                return url;
            }
            return string.Empty;
        }
        /// <summary>
        /// 一个复读机
        /// </summary>
        /// <param name="myqqpost"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<string> Repeater(CallbackMyQQHttpPost myqqpost, MyQQHttpApiRequestInfo info)
        {
            string MQ_msg = myqqpost.MQ_msg.IsUTF8() ? System.Web.HttpUtility.UrlDecode(myqqpost.MQ_msg, Encoding.UTF8) : myqqpost.MQ_msg;

            MyqqHttpApi myqqHttpApi = new(info.Posturl, info.Token);
            MQ_msg = MQ_msg.Replace("复读", "");
            await SendMsgConver(myqqpost, myqqHttpApi, MQ_msg);

            return string.Empty;
        }

        /// <summary>
        /// 回答不懂，可以联系管理员QQ
        /// </summary>
        /// <param name="myqqpost"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task Understand(CallbackMyQQHttpPost myqqpost, MyQQHttpApiRequestInfo info)
        {
            MyqqHttpApi myqqHttpApi = new(info.Posturl, info.Token);
            string msg = "我程序还不是很完善，如有定制需要请联系管理员" + info.MasterQQ;
            await SendMsgConver(myqqpost, myqqHttpApi, msg);

        }

        #region 私有方法
        /// <summary>
        /// 解析回复，包括预定义字段
        /// </summary>
        /// <param name="myqqpost"></param>
        /// <param name="info"></param>
        /// <param name="myqqHttpApi"></param>
        /// <param name="custonOrder"></param>
        /// <returns></returns>
        private async Task parseCustonOrderRequest(CallbackMyQQHttpPost myqqpost, MyQQHttpApiRequestInfo info, MyqqHttpApi myqqHttpApi, OrderData custonOrder)
        {
            var r = new Regex(@"\{(\w+)\}");//大括号内的数据
            var ms = r.Matches(custonOrder.ScriptContent);
            //解析预定义指令
            if (ms.Any())
            {
                foreach (Match match in ms.ToArray())
                {
                    if (match.Success)
                    {
                        if (match.Value == "{taobaofuli}")
                        {
                            await GetBuyersShow(myqqpost, info);
                        }
                        else if (match.Value == "{复读机}")
                        {
                            await Repeater(myqqpost, info);
                        }
                        else if (match.Value == "{不懂}")
                        {
                            await Understand(myqqpost, info);
                        }
                    }
                }
            }
            //直接回复
            else
            {
                await SendMsgConver(myqqpost, myqqHttpApi, custonOrder.ScriptContent);
            }
        }
        /// <summary>
        /// 发送消息时候的对象转换
        /// </summary>
        /// <param name="myqqpost"></param>
        /// <param name="myqqHttpApi"></param>
        /// <param name="sendStr"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        private async Task SendMsgConver(CallbackMyQQHttpPost myqqpost, MyqqHttpApi myqqHttpApi, string sendStr)
        {
            if (myqqpost is null)
            {
                throw new ArgumentNullException(nameof(myqqpost));
            }

            if (myqqHttpApi is null)
            {
                throw new ArgumentNullException(nameof(myqqHttpApi));
            }
            //回复群里面的人自动加上艾特
            if (myqqpost.MQ_type == "2")
            {
                await myqqHttpApi.Api_SendMsg(myqqpost.MQ_robot, myqqpost.MQ_type.ToInt(), myqqpost.MQ_fromID, "", $"[@{myqqpost.MQ_fromQQ}]{sendStr}");
            }
            //私聊时回复
            else if (myqqpost.MQ_type == "1")
            {
                await myqqHttpApi.Api_SendMsg(myqqpost.MQ_robot, myqqpost.MQ_type.ToInt(), myqqpost.MQ_fromID, myqqpost.MQ_fromQQ, sendStr);
            }
            //其他情况
            else
            {
                await myqqHttpApi.Api_SendMsg(myqqpost.MQ_robot, myqqpost.MQ_type.ToInt(), myqqpost.MQ_fromID, "", sendStr);
            }

        }

        #endregion
        #endregion

    }
}
